#import "BBCVC.h"

@implementation BBCView

@synthesize portrait_pos, landscape_pos;

@end

@implementation BBCVC

-(void)addAllBBCViewsInView:(UIView *)v {
	for(UIView * uv in [v subviews])
	{
		BBCView * v = objective_c_cast<BBCView>(uv);
		if( v )
			managed_views.push_back( NSPtr<BBCView>( v ) );
		else {
			[self addAllBBCViewsInView:uv];
		}
	}
}

- (void)viewDidLoad {
	[super viewDidLoad];
//	NSLog(@"self.view %d", int(self.view) );
	[self addAllBBCViewsInView:self.view];
}

-(void)viewDidUnload {
//	NSLog(@"BBCVC viewDidUnload");
	managed_views.clear();
	[super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[self layoutViewsFinalState];
	NSLog(@"BBCVC viewWillAppear");
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
	UIInterfaceOrientation was = [UIApplication sharedApplication].statusBarOrientation;
	bool was_portrait = ( was == UIInterfaceOrientationPortrait || was == UIInterfaceOrientationPortraitUpsideDown );
	[self layoutViewsFinalAlpha:was_portrait];
}

-(void)layoutViewsFinalState {
	UIInterfaceOrientation interfaceOrientation = [UIApplication sharedApplication].statusBarOrientation;
	bool portrait = ( interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown );
	[self layoutViewsFinalAlpha:portrait];
}

-(void)layoutViewsFinalAlpha:(bool)portrait {
	for(BBCList::iterator it = managed_views.begin(); it != managed_views.end(); ++it)
	{
		BBCView * v = it->get();
		UIView * ta = portrait ? v.portrait_pos : v.landscape_pos;
		if( !ta )
			v.alpha = 0;
		else
		{
			v.alpha = ta.alpha;
			v.autoresizingMask = ta.autoresizingMask;
//			NSLog(@"Some view with frame=%@", NSStringFromCGRect(ta.frame));
			v.frame = ta.frame;
		}
	}
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
	bool portrait = ( interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown );
	
	[self layoutViewsFinalAlpha:portrait];
}

- (void)fixStatusBar {
	[[UIApplication sharedApplication] setStatusBarOrientation:[self interfaceOrientation] animated:NO];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
	NSLog(@"BBCVC didRotateFromInterfaceOrientation");
	[self layoutViewsFinalState];
	[self performSelector:@selector(fixStatusBar) withObject:nil afterDelay:0]; // Suggested by Apple Engineers for temporary fix
}

@end
